#!/bin/bash
export LD_LIBRARY_PATH=/usr/local/lib
export PATH=$PATH:/usr/local/bin
function uninit()
{
    #rm /tmp/snd.wav /tmp/snd.mp4  /tmp/src1.avi /tmp/src2.avi /tmp/vid.avi 2> /dev/null
    echo -ne "\a"
    rm -rf $w
    echo
}
w=$(mktemp -d)
if [ -n "$1" ]  ; then
    I="$1"
    test -n "$I" -a -f "$I"  || { echo "give at least one parmeter - film name" ; exit 1 ; }
    S="$2"
    O="${3:-$(basename "$1" .avi).mp4}"
else
    I=`zenity --file-selection --title="plik z filmem"`
    if [ "-z" "$I" ] ; then
	exit 1
    fi
    S=`zenity --file-selection --title="napis"`
    O=`zenity --entry --title="plik wyjsciowy"`.mp4
    if [ "-z" "$O" ] ; then
	exit 1
    fi

    
fi
#exit 1

echo ${PROFILE:=k800}
trap uninit EXIT

mkfifo $w/snd.wav
mkfifo $w/src1.avi
mkfifo $w/src2.avi

#cat "$I" | tee /tmp/src1.avi > /tmp/src2.avi 2> /dev/null &
#> /tmp/src2.avi 2> /dev/null &
#&
mplayer -vc null -ao pcm:fast:file=$w/snd.wav -vo null  "$I" &> /dev/null &
P1=$!
faac -w -o $w/snd.mp4 --obj-type LC $w/snd.wav &> /dev/null &
P2=$!
if [ -z "$4" ] ;  then
mencoder ${S:+-sub "$S"} -profile $PROFILE -nosound -o $w/vid.avi "$I"
else
echo Root password
sudo renice -12 -p $P2

sudo nice -n -17 mencoder ${S:+-sub "$S"} -profile $PROFILE -nosound -o $w/vid.avi "$I"
fi
[ -f "$O" ] && rm "$O"
wait
MP4Box -add $w/snd.mp4 -add $w/vid.avi "$O"

#ffmpeg -i $I snd.wav 2>&1 > /dev/null &